<template>
  <div class="container">
    <div class="card1">
        <el-card>
            <div class="top">
                <div class="title1">订单进度</div>
                <div class="steps">
                <!-- 根据订单状态显示不同的步骤条 -->
                <el-steps :active="steps.active" align-center>
                    <el-step v-for="(step, index) in steps.list" :key="index" :title="step.title">
                        <template #description v-if="step.time">
                            <span class="time">{{ step.time }}</span>
                        </template>
                    </el-step>
                </el-steps>
                </div>
            </div>
        </el-card>
    </div>
    <div class="card2">
        <el-card>
            <div class="top">
                <div class="title1">订单信息</div>
                <div class="orderDetail">
                    <div>
                        <div>订单编号</div>
                        <div>老人姓名</div>
                        <div>护理项目名称</div>
                        <div>下单人</div>
                        <div>备注</div>
                    </div>
                    <div>
                        <div>{{form.orderNo}}</div>
                        <div>{{form.elderly?.name}}</div>
                        <div>{{form.nursingItem?.name}}</div>
                        <div>{{form.orderUser?.nickName}}</div>
                        <div>{{form.remark}}</div>
                    </div>
                    <div>
                        <div>期望服务时间</div>
                        <div>床位号</div>
                        <div>订单金额</div>
                        <div>下单人手机号</div>
                    </div>
                    <div>
                        <div>{{form.expectedServiceTime}}</div>
                        <div>{{form.bed?.bedNo}}</div>
                        <div>{{form.orderAmount}} 元</div>
                        <div>{{form.orderUser?.phonenumber}}</div>
                    </div>
                </div>
            </div>
        </el-card>
    </div>
    <!-- 按钮 -->
    <div class="btn" @click="handleBack">返回</div>
  </div>
</template>

<script setup>
import { onMounted, ref, computed } from 'vue';
import { useRouter } from "vue-router";
import { useRoute } from 'vue-router';

// 获取路由实例
const route = useRoute();
const router = useRouter();

// 读取 query 参数
const orderNo = route.query.orderNo;
const id = route.query.orderId ? Number(route.query.orderId) : null;

console.log('接收的订单ID：', id);

const handleBack=()=>{
    router.push({
        path: `/orderManagement/orderManagementPage`,
      });
}

// 根据订单id获取订单详情
import { getOrderManagement } from "@/api/orderManagement/orderManagement"

const form = ref({})

// 步骤条数据（根据订单状态动态生成）
const steps = ref({
    active: 0,
    list: []
});

/**
 * 根据订单状态生成步骤条数据
 */
const generateSteps = (orderData) => {
    const { orderStatus, transactionStatus, createTime, updateTime, executionTime, refundTime } = orderData;
    
    // 计算完成时间（执行时间的一天后）
    const completionTime = executionTime ? addOneDay(executionTime) : null;
    
    let stepsList = [];
    let activeIndex = 0;

    // 订单状态：0-待支付, 1-待执行, 2-已执行, 3-已完成, 4-已退款, 5-已关闭
    // 交易状态：0-待支付, 1-已支付
    
    if (orderStatus === 0) {
        // 待支付：显示完整流程，但只有已下单是激活状态（蓝色）
        stepsList = [
            { title: '已下单', time: createTime },
            { title: '已支付', time: null },
            { title: '已执行', time: null },
            { title: '已完成', time: null }
        ];
        activeIndex = 1; // active=1 表示第一步完成（已下单为蓝色），其他为灰色
    } else if (orderStatus === 4) {
        // 已退款：若未执行过，不显示已执行，仅显示三个节点
        if (executionTime) {
            // 已执行过：已下单 -> 已支付 -> 已执行 -> 已退款（4步）
            stepsList = [
                { title: '已下单', time: createTime },
                { title: '已支付', time: updateTime },
                { title: '已执行', time: executionTime },
                { title: '已退款', time: refundTime }
            ];
            activeIndex = 4; // 全部激活
        } else {
            // 未执行过：已下单 -> 已支付 -> 已退款（3步）
            stepsList = [
                { title: '已下单', time: createTime },
                { title: '已支付', time: updateTime },
                { title: '已退款', time: refundTime }
            ];
            activeIndex = 3; // 全部激活
        }
    } else if (orderStatus === 5) {
        // 已关闭：只显示已下单 -> 已关闭两个步骤
        stepsList = [
            { title: '已下单', time: createTime },
            { title: '已关闭', time: updateTime }
        ];
        activeIndex = 2; // 两步都完成（全部蓝色）
    } else {
        // 正常流程：已下单 -> 已支付 -> 已执行 -> 已完成
        stepsList = [
            { title: '已下单', time: createTime },
            { title: '已支付', time: orderStatus >= 1 ? updateTime : null },
            { title: '已执行', time: orderStatus >= 2 ? executionTime : null },
            { title: '已完成', time: orderStatus >= 3 ? completionTime : null }
        ];
        activeIndex = orderStatus + 1; // 0->1, 1->2, 2->3, 3->4
    }

    steps.value = {
        active: activeIndex,
        list: stepsList
    };
};

/**
 * 计算日期加一天
 */
const addOneDay = (dateString) => {
    if (!dateString) return null;
    const date = new Date(dateString);
    date.setDate(date.getDate() + 1);
    // 格式化为 YYYY-MM-DD HH:mm:ss
    const year = date.getFullYear();
    const month = String(date.getMonth() + 1).padStart(2, '0');
    const day = String(date.getDate()).padStart(2, '0');
    const hours = String(date.getHours()).padStart(2, '0');
    const minutes = String(date.getMinutes()).padStart(2, '0');
    const seconds = String(date.getSeconds()).padStart(2, '0');
    return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
};

onMounted(() => {
    getOrderManagement(id).then(res => {
        if (res.code === 200) {
            console.log('订单详情完整数据：', JSON.stringify(res.data, null, 2));
            console.log('订单编号：', res.data.orderNo);
            console.log('订单状态：', res.data.orderStatus);
            console.log('退款时间 refundTime：', res.data.refundTime);
            console.log('退款金额 refundAmount：', res.data.refundAmount);
            console.log('退款原因 refundReason：', res.data.refundReason);
            console.log('执行时间 executionTime：', res.data.executionTime);
            form.value = res.data;
            // 生成步骤条数据
            generateSteps(res.data);
        } else {
            console.error('获取订单详情失败：', res.msg);
        }
    });
});

</script>

<style scoped>
.container{
    margin: 15px;
    background-color: #FFFFFF;
    padding: 0px 0px 15px 10px;
}
.el-card{
    /* 宽度沾满整个窗口 */
    width: 100%;
    border-top: none;
    border-right: none;
    /* 保留左边框和下边框（可自定义颜色和宽度） */
    /* 可选：去除默认阴影（如果不需要） */
}
.title1{
    font-size: 20px;
    font-weight: bold;
}
.steps{
    margin-top: 30px;
}
.el-steps{
    width: 100%;
}
.steps .time{
    font-size: 14px;
    color: #909399;
}
/* 订单信息 */
.card2{
    margin-top: 5px;
}

.orderDetail{
    display: flex;
    margin-top: 20px;
}
.orderDetail>div>div{
    height: 50px;
    line-height: 50px;
}
.orderDetail>div:nth-child(1){
    text-align: right;
    margin-right: 30px;
    color: #909399;
}
.orderDetail>div:nth-child(2){
    margin: 0 40px 0px 30px;
}

.orderDetail>div:nth-child(3){
    text-align: right;
    
    color: #909399;
    margin-right: 60px;
}
/* 按钮 */
.btn{
    width: 60px;
    height: 30px;
    line-height: 30px;
    text-align: center;
    background-color: #266FE8;
    color: #FFFFFF;
    border-radius: 5px;
    margin: 20px auto 52px;
}

</style>